package com.test.suanfa;

/**
 * 连表翻转
 * 输入：1->2->3
 * 返回：3->2->1
 */
public class 连表翻转 {

    public static Node queue = null;

    public static void main(String[] args) {
        new 连表翻转().fn3();
    }

    public void fn3(){
        for (int i = 1; i < 5; i++) {
            Node node = new Node(i);
            create(node);
        }
        System.out.println(queue);
        Node prev = null,next = null;
        Node curr = queue;
        while (curr != null){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        System.out.println(prev);
    }

    public void fn2() {
        for (int i = 1; i < 5; i++) {
            Node node = new Node(i);
            create(node);
        }
        System.out.println(queue);
        Node prev = null,next;
        Node curr = queue;
        while (curr!=null){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        System.out.println(prev);
    }

    public void fn1() {
        for (int i = 1; i < 5; i++) {
            Node node = new Node(i);
            create(node);
        }
        System.out.println(queue);
        Node prev = null, next = null;
        Node curr = queue;
        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        System.out.println(prev);
    }

    public static void test1() {
        for (int i = 1; i < 5; i++) {
            Node node = new Node(i);
            create(node);
        }
        System.out.println(queue);
        Node prev = fanzhuan();
        System.out.println(prev);
    }

    public static Node fanzhuan() {
        Node prev = null, next;
        Node curr = queue;
        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;  // 此时 (prev)1<-1(curr)->2->3(next)
            curr = next;
        }
        return prev;
    }

    public static void create(Node node) {
        if (queue == null) {
            node.setNext(null);
            queue = node;
        } else {
            node.setNext(queue);
            queue = node;
        }
    }

    static class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}
